package cn.net.yto.school.web.course;

import cn.net.yto.base.dao.entities.TAccount;
import cn.net.yto.base.dao.pagination.PaginationRequest;
import cn.net.yto.base.dao.pagination.PaginationResponse;
import cn.net.yto.base.shiro.util.ShiroUserHelper;
import cn.net.yto.base.util.RequestHandler;
import cn.net.yto.school.dao.entities.TbCourse;
import cn.net.yto.school.dao.entities.TbFile;
import cn.net.yto.school.service.CourseService;
import cn.net.yto.school.service.FileService;
import cn.net.yto.school.web.sparm.StaticParamClazz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

@Controller
@RequestMapping("/course")
public class CourseCotroller {

    @Autowired
    private CourseService courseService;

    @Autowired
    private FileService fileService;

    @RequestMapping("query")
    public String query(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "course/course_init";
    }

    @RequestMapping("list")
    public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
        PaginationRequest paginationRequest = RequestHandler.buildPaginationRequest(request, model);
        PaginationResponse<TbCourse> paginationResponse = this.courseService.findResultsByPagination(paginationRequest);
        model.addAttribute("paginationResponse", paginationResponse);

        return "course/course_list";
    }

    @RequestMapping("delete/{id}")
    public String delete(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") Integer id) {
        this.courseService.deleteCourseById(id);

        return "redirect:/course/query";
    }

    @RequestMapping(value = {"add"}, method = {RequestMethod.GET})
    public String addCourse(HttpServletRequest request, HttpServletResponse response, Model model) {

        return "course/course_add";
    }

    @RequestMapping(value = {"add"}, method = {RequestMethod.POST})
    public String addCourseHandler(HttpServletRequest request, HttpServletResponse response, Model model) {

        TbCourse course = (TbCourse) RequestHandler.createBean(request, new TbCourse());

        TAccount account = new TAccount();
        account.setId(ShiroUserHelper.getCurrentShiroUser().getId());
        course.setActor(account);

        this.courseService.saveCourse(course);

        return "redirect:/course/query";
    }

    @RequestMapping(value = {"edit/{id}"}, method = {RequestMethod.GET})
    public String editCourse(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") Integer id) {

        model.addAttribute("course", this.courseService.findOne(id));

        return "course/course_edit";
    }

    @RequestMapping(value = {"edit"}, method = {RequestMethod.POST})
    public String editCourseHandler(HttpServletRequest request, HttpServletResponse response, Model model) {

        TbCourse course = (TbCourse) RequestHandler.createBean(request, new TbCourse());

        //增加最后一次操作员数据
        TAccount account = new TAccount();
        account.setId(ShiroUserHelper.getCurrentShiroUser().getId());
        course.setActor(account);

        this.courseService.saveCourse(course);

        return "redirect:/course/query";
    }

    @RequestMapping(value = {"add/file/{id}"}, method = {RequestMethod.GET})
    public String addFileToCourse(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") Integer id) {
        //获取到课程id
        Integer courseId = id;

        //通过课程id查询tb_file表中所有文件
        List<TbFile> files = this.courseService.findResultsByCourseId(courseId);

        //将文件返回
        model.addAttribute("files", files);

        //将课程id放在session里
        request.getSession().setAttribute("courseId", courseId);

        return "course/course_show_files";
    }

    @RequestMapping(value = {"file/add"}, method = {RequestMethod.GET})
    public String uploadFileWithCourse(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "course/course_upload_files";
    }

    @RequestMapping(value = {"file/add"}, method = {RequestMethod.POST})
    public String uploadFileWithCourseHandler(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam("file") MultipartFile file, String fileContent) throws Exception {
        Integer courseId = (Integer) request.getSession().getAttribute("courseId");

        String fileName = uploadFileHandler(file);

        //文件成功上传以后将文件信息写在数据库中
        TbFile f = new TbFile();
        f.setFileName(fileName);
//        f.setFilePath(StaticParamClazz.FILE_UPLOAD_ROOT_PATH + File.separator + fileName);
        f.setFilePath(fileName);
        TbCourse tc = new TbCourse();
        tc.setId(courseId);
        f.setFileBelongTo(tc);
        f.setFileDiscrib(fileContent);
        f.setFileDownloadCount(0);

        //增加最后一次操作员数据
        TAccount account = new TAccount();
        account.setId(ShiroUserHelper.getCurrentShiroUser().getId());
        f.setActor(account);

        //保存文件信息到数据库
        this.fileService.saveFile(f);

        request.getSession().removeAttribute("courseId");

        return "redirect:/index";
    }

    public static String uploadFileHandler(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 文件存放服务端的位置
                File dir = new File(StaticParamClazz.FILE_UPLOAD_ROOT_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                // 写文件到服务器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);
                return file.getOriginalFilename();
            } catch (Exception e) {
                return "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + file.getOriginalFilename() + " because the file was empty.";
        }
    }
}
